<template>
  <div class="note-detail-root-page">
    <div class="note-detail-main">
      <div class="header">
        <div class="title">{{ title }}</div>

        <div class="note-header-info">
          <div class="left">
            <div class="user-head-picture">
              <img :src="user.headPicture || defaultUserImg" alt="" />
            </div>
            <div class="user-info">
              <div class="username" v-if="isShowUser">
                作者：<span @click.stop="toAuthor" class="compellation">{{
                  user.username
                }}</span>
              </div>
              <div class="tags">
                书签：{{
                  tags.map((tag) => tag.tagname).join("、") || "------"
                }}
              </div>
              <div class="viewCount">
                浏览：<span>{{ viewCount }}</span>
              </div>
            </div>
          </div>
          <div class="right">
            <div class="updated-at" v-if="updated_at">
              更新时间：{{ updated_at }}
            </div>
            <div class="created-at" v-else>发稿时间：{{ created_at }}</div>
          </div>
        </div>
      </div>
      <div class="editor-content-view" id="essay-content" v-highlight>
        <div v-html="content"></div>
      </div>
    </div>

    <div class="action-png" @click="downloadPng">png</div>
    <div class="action-pdf" @click="downloadPdf">pdf</div>
  </div>
</template>

<script>
import "./custom-wangeditor.scss"; // 引入 css
import { onMounted, ref, computed } from "vue";
import html2canvas from "html2canvas";
// 引入jsPDF库
import jsPDF from "jspdf";
import request from "utils/request";
import { addWaterMarker } from "utils/addWaterMarker.js";
import { getParamsCode } from "utils/getParamsCode";

export default {
  name: "JddChromePluginsNoteDetail",
  setup() {
    const id = getParamsCode("id");
    const isShowUser = ref(false);
    const title = ref("");
    const content = ref("");
    const viewCount = ref(0);
    const updated_at = ref("");
    const created_at = ref("");
    const user = ref({});
    const tags = ref([]);
    const watermarking = ref(false);

    const downloadPng = () => {
      const content = document.getElementById("essay-content");

      html2canvas(content, {
        allowTaint: true,
        scale: 2, // 提升画面质量，但是会增加文件大小
        useCORS: true, // 允许使用CORS资源
      }).then(function (canvas) {
        const link = document.createElement("a");
        link.href = canvas.toDataURL("image/png");
        // link.download =`image.png`  // 下载文件的名称
        link.download = title.value;
        link.style.display = "none";
        // 将a标签追加到文档对象中
        document.body.appendChild(link);
        // 模拟点击了<a>标签,会触发<a>标签的href的读取,浏览器就会自动下载了
        link.click();
        // 一次性的,用完就删除a标签
        link.remove();
      });

    };

   const downloadPdf = ()=>{
      const content = document.getElementById("essay-content");
      html2canvas(content, {
        allowTaint: true,
        scale: 2, // 提升画面质量，但是会增加文件大小
        useCORS: true, // 允许使用CORS资源
      }).then(function (canvas) {
        /**jspdf将html转为pdf一页显示不截断，整体思路：
         * 1. 获取DOM
         * 2. 将DOM转换为canvas
         * 3. 获取canvas的宽度、高度（稍微大一点）
         * 4. 将pdf的宽高设置为canvas的宽高
         * 5. 将canvas转为图片
         * 6. 实例化jspdf，将内容图片放在pdf中（因为内容宽高和pdf宽高一样，就只需要一页，也防止内容截断问题）
         */

        // 得到canvas画布的单位是px 像素单位
        var contentWidth = canvas.width;
        var contentHeight = canvas.height;

        console.log("contentWidth", contentWidth);
        console.log("contentHeight", contentHeight);
        // 将canvas转为base64图片
        var pageData = canvas.toDataURL("image/png", 1.0);

        // 设置pdf的尺寸，pdf要使用pt单位 已知 1pt/1px = 0.75   pt = (px/scale)* 0.75
        // 2为上面的scale 缩放了2倍
        var pdfX = ((contentWidth + 10) / 2) * 0.75;
        var pdfY = ((contentHeight + 500) / 2) * 0.75; // 500为底部留白

        // 设置内容图片的尺寸，img是pt单位
        var imgX = pdfX;
        var imgY = (contentHeight / 2) * 0.75; //内容图片这里不需要留白的距离

        // 初始化jspdf 第一个参数方向：默认''时为纵向，第二个参数设置pdf内容图片使用的长度单位为pt，第三个参数为PDF的大小，单位是pt
        var PDF = new jsPDF("", "pt", [pdfX, pdfY]);

        // 将内容图片添加到pdf中，因为内容宽高和pdf宽高一样，就只需要一页，位置就是 0,0
        PDF.addImage(pageData, "jpeg", 0, 0, imgX, imgY);
        PDF.save(title.value + ".pdf");
      });
    };

    onMounted(async () => {
      if (id) {
        let ret = await request.get(`/essay/${id}`);
        if (ret.code == 200) {
          document.title = ret.data.essaytitle;
          isShowUser.value = !ret.data.del;
          title.value = ret.data.essaytitle;
          viewCount.value = ret.data.view_count;
          content.value = ret.data.content;
          updated_at.value = ret.data.updated_at;
          created_at.value = ret.data.created_at;
          user.value = ret.data.user;
          tags.value = ret.data.tags;
          watermarking.value = ret.data.watermarking;
          let Root = document.getElementById("essay-root");
          watermarking.value &&
            addWaterMarker(`${user.value.username}`, Root, "16px Georgia");
        }
      }
    });

    const toAuthor = () => {
      window.open(
        // "/nest-vue-short-passage-front/home.html?id=" + user.value.id,
        "/blog/home.html",
        "__blank"
      );
    };

    const defaultUserImg = computed(() => {
      return require("src/assets/user-header.png");
    });

    return {
      title,
      viewCount,
      isShowUser,
      content,
      user,
      tags,
      created_at,
      updated_at,
      toAuthor,
      defaultUserImg,
      downloadPng,
      downloadPdf
    };
  },
};
</script>



<style lang="scss" scoped>
.note-detail-root-page {
  overflow-y: auto;
  overflow-x: hidden;
  height: 100vh;
  background: #f8f8f8;
}

.note-detail-main {
  width: 1050px;
  margin: 0 auto;
  height: 100%;
  padding: 15px 0px;
  box-sizing: border-box;
  background: white;
  .header {
    text-align: center;
    font-size: 22px;
    line-height: 36px;
    color: #000;
    margin-bottom: 20px;
    .note-header-info {
      display: flex;
      align-items: flex-end;
      justify-content: space-between;
      padding: 0px 20px;
      color: #8590a6;
      font-size: 13px;
      .left {
        display: flex;
        align-items: flex-end;
        text-align: left;
        .user-head-picture {
          width: 80px;
          height: 80px;
          border-radius: 50%;
          overflow: hidden;
          cursor: pointer;
          margin-right: 10px;
          img {
            width: 100%;
            height: 100%;
          }
        }
        .user-info {
          font-size: 14px;
          div {
            line-height: 24px;
          }
          .tags {
            max-width: 350px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
          .username {
            cursor: pointer;
            .compellation {
              color: #056de8;
            }
          }
        }
      }
      .right {
        font-size: 14px;
      }
    }
    .title {
      font-family: "Comic Sans MS", cursive, sans-serif;
      // text-shadow: 0 0 2px hsl(40, 28.57%, 28.82%),
      //   0 0 2px hsl(40, 28.57%, 28.82%), 0 0 2px hsl(40, 28.57%, 28.82%); /*多个叠加*/
      font-size: 25px;
      color: black;
      margin: 20px 0px 20px;
    }
  }
  .editor-content-view {
    color: #4d4d4d;
    font-size: 15px;
    padding-bottom: 80px;
  }
}

@media screen and (max-width: 850px) {
  .note-detail-main {
    width: 100%;
    .header {
      .note-header-info {
        flex-direction: column;
        align-items: unset !important;
        justify-content: unset !important;
        text-align: left !important;
        .left {
          .user-info {
            .tags {
              max-width: 200px;
            }
          }
        }
      }
    }
  }
}

.action-png {
  position: fixed;
  width: 50px;
  height: 50px;
  bottom: 80px;
  right: 50px;
  border-radius: 50%;
  overflow: hidden;
  text-align: center;
  line-height: 50px;
  background-color: #fff;
  font-size: 15px;
  color: #409eff;
  z-index: 999;
  box-shadow: 0px 1px 8px 0px rgba(0, 0, 0, 0.08);
}

.action-pdf{
  position: fixed;
  width: 50px;
  height: 50px;
  bottom: 140px;
  right: 50px;
  border-radius: 50%;
  overflow: hidden;
  text-align: center;
  line-height: 50px;
  background-color: #fff;
  font-size: 15px;
  color: #409eff;
  z-index: 999;
  box-shadow: 0px 1px 8px 0px rgba(0, 0, 0, 0.08);
}

@media screen and (max-width: 850px) {
  .action-png, .action-pdf {
    display: none !important;
  }
}



</style>
